import * as moment from 'moment';

export class DateTimeHelper {
    public static readonly MillisecondsOfDay: number = 1000 * 60 * 60 * 24;

    static addDays(date, days): Date {
        let result = new Date(date);
        result.setDate(result.getDate() + days);
        return result;
    }

    // 判断是否为闰年
    static isLeapYear(year: number): boolean {
        if (year <= 0) {
            return false;
        }

        return year % 400 === 0 || (year % 100 !== 0 && year % 4 === 0);
    }

    // 返回指定年月的天数
    static daysInMonth(year: number, month: number): number {
        return new Date(year, month, 0).getDate();
    }

    // check date format with specified parameters.
    static isValidDate(year: number, month: number, day: number, notInFuture?: boolean): boolean {
        if (isNaN(year) || isNaN(month) || isNaN(day)) {
            return false;
        }

        if (year < 1905 || year > 9999 || month < 0 || month > 12 || day > 31 || day <= 0) {
            return false;
        }

        let numDays = DateTimeHelper.daysInMonth(year, month);

        // Check the day
        if (day <= 0 || day > numDays[month - 1]) {
            return false;
        }

        if (notInFuture === true) {
            let currentDate = new Date(),
                currentYear = currentDate.getFullYear(),
                currentMonth = currentDate.getMonth(),
                currentDay = currentDate.getDate();
            return (year < currentYear
                || (year === currentYear && month - 1 < currentMonth)
                || (year === currentYear && month - 1 === currentMonth && day < currentDay));
        }

        return true;
    }

    static getCurrentTimestamp(): number {
        return moment().valueOf();
    }

    static getEndOfTodayTimestamp(): number {
        return moment.utc().hour(23).minute(59).second(59).valueOf();
    }

    static toUTCTimestamp(timestamp: number): number {
        let dateString = moment(timestamp).format("YYYY-MM-DD HH:mm:ss.SSS");
        return moment.utc(dateString).valueOf();
    }

    static getZoneName(date: string | Date | number): string {
        try {
            let dateStr = new Date(moment(date).toString()).toString();
            return dateStr.substr(dateStr.indexOf('('));
        } catch {
            return '';
        }
    }

    static getEndOfDate(date: Date): number {
        return moment(date).hour(23).minute(59).second(59).valueOf();
    }

    static getStartOfDate(date: Date): number {
        return moment(date).hour(0).minute(0).second(0).valueOf();
    }
}
